<template>
  <el-card>
    <bread data1="商品管理" data2="商品列表" path1="/goods"></bread>
    <!-- 提示条 -->
    <el-alert
      title="添加商品信息"
      type="success"
      show-icon
      center
      class="prompt"
    >
    </el-alert>
    <!-- 步骤条 -->
    <el-steps :active="active - 0" finish-status="success" simple align-center>
      <el-step title="基本信息"></el-step>
      <el-step title="商品参数"></el-step>
      <el-step title="商品属性"></el-step>
      <el-step title="商品图片"></el-step>
      <el-step title="商品内容"></el-step>
    </el-steps>
    <!-- tab切换 最外层要是一个表单包裹，因为整个数据提交和登录很像，里面的数据要在fomr-item里面 -->
    <el-form label-position="top" label-width="80px" :model="form" class="form">
      <el-tabs tabPosition="left" v-model="active" @tab-click="clicktab">
        <el-tab-pane name="1" label="基本信息">
          <el-form-item label="商品名称">
            <el-input v-model="form.goods_name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="商品价格">
            <el-input v-model="form.goods_price" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="商品数量">
            <el-input v-model="form.goods_number" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="商品重量">
            <el-input v-model="form.goods_weight" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="商品分类">
            <el-cascader
              v-model="value"
              :options="categories"
              :props="prpoes"
              @change="handerchange"
            ></el-cascader>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane name="2" label="商品参数">
          <!-- 选择的三级分类的参数 -->
          <el-form-item
            v-for="item in arrDynamic"
            :key="item.attr_id"
            :label="item.attr_name"
          >
            <!-- v-model 存放的是选中的值 所以把item.attr_vals这个现为数组的值给它，则就会全部选中 -->
            <el-checkbox-group v-model="item.attr_vals">
              <el-checkbox
                :label="item2"
                border
                v-for="(item2, i) in item.attr_vals"
                :key="i"
              ></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane name="3" label="商品属性">
          <el-form-item
            v-for="item in staticParameters"
            :key="item.attr_id"
            :label="item.attr_name"
          >
            <el-input v-model="item.attr_vals"></el-input>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane name="4" label="商品图片">
          <!-- 点击上传的时候并不会·真的上传而是在图片信息存储在服务器中，而这个请求也需要请求头 
          服务端的server文件下的tmp_uploads就会有文件     -->
          <el-form-item v-if="this.value.length === 3">
            <el-upload
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :headers="headers"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :file-list="fileList"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane name="5" label="商品信息">
          <el-form-item v-if="this.value.length === 3">
            <el-button type="danger" @click="addGoods">添加商品</el-button>
            <quill-editor v-model="form.introduce"></quill-editor>
          </el-form-item>
        </el-tab-pane>
      </el-tabs>
    </el-form>
  </el-card>
</template>

<script>
// 富文本组件
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { quillEditor } from "vue-quill-editor";
export default {
  components: {
    quillEditor
  },
  data() {
    return {
      active: "1",
      // form的key要根据需添加的值来填写
      form: {
        goods_name: "",
        goods_cat: "", //就是级联选择器 的值但是要用字符串
        goods_price: "",
        goods_number: "",
        goods_weight: "",
        goods_introduce: "",
        // 图片的临时路径
        pics: [],
        //静态参数和动态参数放在一起
        attrs: []
      },
      prpoes: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      categories: [],
      // value和级联选择器的v-model双向绑定，
      // 里面可以填写prpoes里面value的值 如果填写 就会默认显示出label对应的值
      value: [],
      // 动态参数
      arrDynamic: [],
      // 静态参数
      staticParameters: [],
      // 图片
      fileList: [],
      //设置图片上传的请求的头部
      headers: {
        Authorization: localStorage.getItem("token")
      }
    };
  },
  created() {
    this.getcategories();
  },
  methods: {
    async getcategories() {
      const res = await this.$http.get(`categories?type=3`);
      this.categories = res.data.data;
    },
    // 点击不同的tab,e为对应的tab实例
    async clicktab(e) {
      // active和el-tabs 对应的子组件下标绑定
      if (this.active !== "1") {
        // 如果不等于三 则没有选择三级的分类
        if (this.value.length !== 3) {
          this.$message.warning("请选择三级分类");
          return;
        } else if (this.active === "2") {
          // 进行商品参数请求,id为value数组的第三值
          const res = await this.$http.get(
            `categories/${this.value[2]}/attributes?&sel=many`
          );
          this.arrDynamic = res.data.data;
          this.arrDynamic.forEach(item => {
            //  需要从新赋值，因为split返回新的字符串 原字符串不变
            // 有的没有三级数组 所以遍历之后会报错
            item.attr_vals =
              item.attr_vals.length === 0
                ? []
                : item.attr_vals.trim().split(",");
          });
        } else if (this.active === "3") {
          // 商品的静态属性
          const res1 = await this.$http.get(
            `categories/${this.value[2]}/attributes?&sel=only`
          );
          this.staticParameters = res1.data.data;
        }
      }
    },
    //点击文件列表中已上传的文件时
    //file 图片的信息
    handlePreview(file) {},
    // 图片列表移除文件时
    handleRemove(file) {
      console.log(file);
      let index = this.form.pics.findIndex(
        el => el.pic === file.response.data.tmp_path
      );
      if (index !== -1) {
        this.form.pics.splice(index, 1);
      }
      console.log(this.form.pics);
    },
    handerchange(file) {},
    //图片上传成功的时候
    handleSuccess(file) {
      this.form.pics.push({
        pic: file.data.tmp_path
      });
      console.log(file);
    },
    // 添加商品
    async addGoods() {
      //  goods_cat 处理 就是级联选择器 的值用字符串
      this.form.goods_cat = this.value.join(",");
      console.log(this.form.goods_cat);
      //  atts 处理商品的参数（数组），包含 `动态参数` 和 `静态属性` [ {  "attr_id":15,"attr_value":"ddd"}]
      let arr1 = this.arrDynamic.map(item => {
        return { attr_id: item.attr_id, attr_value: item.attr_vals.join(",") };
      });
      let arr2 = this.staticParameters.map(item => {
        return { attr_id: item.attr_id, attr_value: item.attr_vals };
      });
      this.form.attrs = [...arr1, ...arr2];
      const res = await this.$http.post("goods", this.form);
      console.log(res);
      this.$router.push("/goods");
    }
  }
};
</script>

<style lang="scss" scoped>
.prompt {
  margin: 20px 0 15px 0;
}
.form {
  margin-top: 25px;
  height: 320px;
  overflow: auto;
}
.quill-editor {
  margin-top: 5px;
  .ql-editor {
    min-height: 300px;
  }
}
</style>
